package com.wjx.collect;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;

public class Collect {
    private static final Logger logger = LoggerFactory.getLogger(Collect.class);
    private Robot robot;
    private int currentPrefix = 50;
    private int currentIndex = 1;
    private static final int TOTAL_RECORDS = 230;
    private static final String WJX_URL = "https://wcsmsurvey.wjx.com/resultquery.aspx?activity=298775450";

    public Collect() throws AWTException {
        this.robot = new Robot();
        robot.setAutoDelay(100);
    }

    public void start() {
        try {
            logger.info("程序启动，开始数据采集...");

            while (currentIndex <= TOTAL_RECORDS && currentPrefix <= 9999) {
                if (!checkAndOpenPage()) {
                    openBrowser();
                    Thread.sleep(500);
                    continue;
                }

                String queryId = generateQueryId();
                logger.info("开始查询ID: {}", queryId);

                if (searchAndVerify(queryId)) {
                    currentIndex++;
                }
                currentPrefix++;
                Thread.sleep(500);
            }

            logger.info("数据采集完成，共采集{}条记录", currentIndex - 1);

        } catch (Exception e) {
            logger.error("程序运行异常: ", e);
        }
    }

    private boolean checkAndOpenPage() {
        try {
            // 移动鼠标到标题位置并选择文本
            robot.mouseMove(914, 350);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(100);
            robot.mouseMove(1002, 350);
            robot.delay(100);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

            // Ctrl+C 复制
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_C);
            robot.delay(100);
            robot.keyRelease(KeyEvent.VK_C);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(100);  // 等待复制完成

            // 获取剪贴板内容
            String text = getClipboardText();
            logger.info("获取到的文本内容: {}", text);

            return text != null && text.contains("对外查询");

        } catch (Exception e) {
            logger.error("检查页面异常: ", e);
            return false;
        }
    }

    private void openBrowser() {
        try {
            // 按下Alt + D 选择地址栏
            robot.keyPress(KeyEvent.VK_ALT);
            robot.keyPress(KeyEvent.VK_D);
            robot.keyRelease(KeyEvent.VK_D);
            robot.keyRelease(KeyEvent.VK_ALT);
            robot.delay(100);

            // 将网址复制到剪贴板
            setClipboardText(WJX_URL);

            // Ctrl+V 粘贴
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(100);

            // 按下回车
            robot.keyPress(KeyEvent.VK_ENTER);
            robot.keyRelease(KeyEvent.VK_ENTER);
            logger.info("输入网址并回车: {}", WJX_URL);
        } catch (Exception e) {
            logger.error("输入网址异常: ", e);
        }
    }

    private String generateQueryId() {
        return String.format("%04d%04d", currentPrefix, currentIndex);
    }

    private boolean searchAndVerify(String queryId) {
        try {
            // 定位输入框
            Point inputPoint = findInputBoxLocation();
            robot.mouseMove(inputPoint.x, inputPoint.y);
            mouseClick();

            // 清空输入框
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_A);
            robot.keyRelease(KeyEvent.VK_A);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_DELETE);
            robot.keyRelease(KeyEvent.VK_DELETE);

            // 将查询ID复制到剪贴板并粘贴
            setClipboardText(queryId);
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_V);
            robot.keyRelease(KeyEvent.VK_CONTROL);

            // 点击查询按钮
            Point searchButton = findSearchButtonLocation();
            robot.mouseMove(searchButton.x, searchButton.y);
            mouseClick();

            Thread.sleep(2000);

            // 检查是否查询成功
            if (!checkQueryFailed() && checkQuerySuccess()) {
                saveScreenshots(queryId);
                return true;
            }
            return false;

        } catch (Exception e) {
            logger.error("查询过程发生异常: ", e);
            return false;
        }
    }

    private void mouseClick() {
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.delay(100);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    }

    private Point findInputBoxLocation() {
        // 输入框位置固定在指定坐标
        return new Point(850, 490);
    }

    private Point findSearchButtonLocation() {
        // 查询按钮位置相对固定
        return new Point(962, 556);
    }

    private boolean checkQueryFailed() {
        try {
            // 选择错误提示区域
            robot.mouseMove(811, 595);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(100);
            robot.mouseMove(1107, 595);
            robot.delay(200);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

            // Ctrl+C 复制
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_C);
            robot.delay(200);
            robot.keyRelease(KeyEvent.VK_C);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(200);

            String text = getClipboardText();
            logger.info("查询结果文本: {}", text);

            return text != null && (text.contains("没有查询到结果") || text.contains("请确认所填信息正确无误"));

        } catch (Exception e) {
            logger.error("检查查询结果异常: ", e);
            return true;
        }
    }

    private boolean checkQuerySuccess() {
        try {
            // 选择错误提示区域
            robot.mouseMove(530, 207);
            robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robot.delay(100);
            robot.mouseMove(592, 207);
            robot.delay(100);
            robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

            // Ctrl+C 复制
            robot.keyPress(KeyEvent.VK_CONTROL);
            robot.keyPress(KeyEvent.VK_C);
            robot.delay(100);
            robot.keyRelease(KeyEvent.VK_C);
            robot.keyRelease(KeyEvent.VK_CONTROL);
            robot.delay(100);

            String text = getClipboardText();
            logger.info("查询结果文本: {}", text);

            return text != null && text.contains("查询条件");

        } catch (Exception e) {
            logger.error("检查查询结果异常: ", e);
            return true;
        }
    }

    private void saveScreenshots(String queryId) {
        try {
            // 确保查询成功后再创建目录和保存图片
            File picDir = new File("pic");
            if (!picDir.exists()) {
                picDir.mkdirs();
            }

            // 截取第一张图
            BufferedImage capture1 = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            ImageIO.write(capture1, "png", new File(picDir, queryId + "_1.png"));

            // 滚动到底部
            robot.mouseWheel(10);
            Thread.sleep(1000);

            // 截取第二张图
            BufferedImage capture2 = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            ImageIO.write(capture2, "png", new File(picDir, queryId + "_2.png"));

            logger.info("查询成功并保存截图: {}", queryId);

        } catch (Exception e) {
            logger.error("截图保存异常: ", e);
        }
    }

    private void setClipboardText(String text) {
        StringSelection stringSelection = new StringSelection(text);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
    }

    // 获取剪贴板内容
    private String getClipboardText() {
        try {
            Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
            if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return (String) transferable.getTransferData(DataFlavor.stringFlavor);
            }
        } catch (Exception e) {
            logger.error("获取剪贴板内容异常: ", e);
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            new Collect().start();
        } catch (Exception e) {
            logger.error("程序启动异常: ", e);
        }

    }
}
